package com.atguigu.lease.common.minio;

import io.minio.*;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
@Slf4j
public class  MinioUtil {

    @Autowired
    private MinioProperties minioProperties;

    private MinioClient minioClient;

    //初始化客户端
    @PostConstruct
    public void init() {
        minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccesskey(), minioProperties.getSecretKey())
                .build();
    }

    //上传文件
    public String uploadFile(MultipartFile file) {
        String bucketName = minioProperties.getBucketName();
        try {
            // 确保 Bucket 存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }

            // 生成唯一文件名
            String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "_"
                    +UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 设置文件权限为公开
            setPublicPolicy(bucketName);

            // 返回文件 URL
            return minioProperties.getEndpoint() + "/" + bucketName + "/" + fileName;
        } catch (Exception e) {
            log.error("上传文件失败：{}", e.getMessage());
            return null;
        }
    }

    private void setPublicPolicy(String bucketName) {
        String policy = String.format("""
        {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": "*",
              "Action": ["s3:GetObject"],
              "Resource": ["arn:aws:s3:::%s/*"]
            }
          ]
        }
        """, bucketName);
        try {
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(bucketName)
                            .config(policy)
                            .build()
            );
        } catch (Exception e) {
            log.error("设置 Bucket 公开访问失败：{}", e.getMessage());
        }
    }

    //下载功能备用
    public String getFileUrl(String fileName) {
        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
    }

}
